package com.bo.weibo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bo.WeiboConfig;
import com.bo.gather.GatherService;
import com.bo.gather.bean.GatherBean;
import com.bo.gather.rule.RuleService;
import com.bo.util.IOUtil;
import com.bo.util.UnicodeConverter;

public class SearchAccount {
	static Logger log = Logger.getLogger(SearchAccount.class.getName());
	private static  List<String> accountNickList = Collections.synchronizedList(new ArrayList<String>()); 
//	private static  Map<String,Integer> onlyaccountNickMap =Collections.synchronizedMap(new HashMap<String,Integer>()); 
	
	private static boolean putIfAbsent(String x) {  
        synchronized (accountNickList) {  
        	boolean absent = !accountNickList.contains(x);  
            if (absent) 
            	accountNickList.add(x);  
            return absent;  
        }  
    } 
	
//	private static boolean putIfAbsentMap(String x) {  
//        synchronized (accountNickList) {  
//        	boolean absent = onlyaccountNickMap.get(x)==null;  
//            if (absent) 
//            	onlyaccountNickMap.put(x, 1);  
//            return absent;  
//        }  
//    } 
	
	public static synchronized String getAccountNick(String searchdata) {  
        synchronized (accountNickList) {
        	if(accountNickList.size()>1){//2个以上才能获取
        		String nick=accountNickList.get(0);
        		if(isRepeat(nick)){
        			IOUtil.writeEndData(WeiboConfig.getValue("weiboNickName").trim(), nick+"\r\n", "UTF-8");
        			accountNickList.remove(nick);
        			return nick;
        		}else{
        			return getAccountNick(searchdata);
        		}
        	}else{
        		List<String> templist=searchAccountNick(searchdata);
        		for(String s:templist){
//        			if(putIfAbsentMap(s)){
        				putIfAbsent(s); 
//        			}
        		}
        	}
            return getAccountNick(searchdata);  
        }  
    }
	
	private static List<String> searchAccountNick(String searchdata) { 
		//:[0-9]clean:[a-y]clean:[A-Y]clean:\\pP|\\pSclean  过滤数字 字母 标点符号 空格
		searchdata=searchdata.replaceAll("[0-9]", "").replaceAll("[a-y]", "").replaceAll("\\pP|\\pS", "").replaceAll(" ", "");
		//过滤重复的汉字
		Map<String,String> map=new HashMap<String,String>();
		GatherService gatherService=new GatherService();
		if(searchdata!=null && searchdata.length()>0){
			String rulestr=null;
			try {
				File file=new File(WeiboConfig.getValue("caijiRule").trim()+"20130214163515");
				rulestr = IOUtil.readFileToString(file,  "utf-8");
			} catch (IOException e) {
				e.printStackTrace();
			}
			GatherBean gatherbean=null;
			List<Map<String,String>> resultlist=new ArrayList<Map<String,String>>();
			if(rulestr!=null && rulestr.length()>0){
				RuleService rule=new RuleService();
				gatherbean=rule.calculateRule(rulestr);
			}
			//不要太多文字
			int length=searchdata.length()>5?5:searchdata.length();
			for(int i=0;i<length;i++){
				String key=String.valueOf(searchdata.charAt(i));
				map.put(key,key);
			}
			log.info("进行微博昵称搜索,搜索内容为："+map.keySet());
			String start="http://s.weibo.com/weibo/"; //%25E5%2593%258E&xsort=time&scope=ori
			String end="&xsort=time&scope=ori";
			for(String s:map.keySet()){
				try {
					StringBuffer sb=new StringBuffer();
					sb.append(start);
					s = java.net.URLEncoder.encode(s, "utf-8");
					sb.append(s);
					sb.append(end);
					
					if(gatherbean!=null){
//						System.out.println(sb.toString());
						String []array={sb.toString()};
						gatherbean.setParentUrl(array);
						gatherService.calculateParentContent(gatherbean, resultlist);
					}
					Thread.sleep(10000);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			List<String> list=new ArrayList<String>();
			for(Map<String,String> mapnick:resultlist){
				String nick=mapnick.get(gatherbean.getParentContent().get(0).getName());
				nick=UnicodeConverter.fromEncodedUnicode(nick.toCharArray(), 0, nick.length());
				list.add(nick);
			}
			return list;
		}
		return null;
	}
	
	
	
	
	
	public static boolean  isRepeat(String nickname){
		File file=new File(WeiboConfig.getValue("weiboNickName").trim());
		if(file.exists()){
			BufferedReader in = null;
			String currLine = null;
			try {
				InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");   
				in = new BufferedReader(isr);
				while ((currLine = in.readLine()) != null) {
					if (currLine.trim().equals("")) {
						continue;
					}
					if(currLine.equals(nickname)){
						return false;
					}
				}
			}catch(Exception io){
				io.printStackTrace();
			} finally {
				try {
					in.close();
				} catch (IOException ex) {				
				}
				in = null;
			}
		}
		
		return true;
	}
	
	
	
	
	
	
	
	public static void main(String[] args) {
		getAccountNick("发起来了");
		getAccountNick("");
	}
}
